package com.example.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.entity.LoginUser;
import com.example.entity.User;
import com.example.mapper.MenuMapper;
import com.example.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author cjd
 * @date 2024/01/30 23:33
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 1、查询用户信息（认证）
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserName, username));
        // 用户不存在就抛出异常，security框架会自动处理
        if (Objects.isNull(user)){
            throw new RuntimeException("用户名或者密码错误");
        }

        // 查询对应的权限信息（授权），添加到LoginUser中
        List<String> list = menuMapper.selectPermsByUserId(user.getId());

        // 封装成LoginUser对象，返回给security框架
        return new LoginUser(user,list);
    }
}
